package com.zxy.ziems.server.alarm.client;

import com.zxy.btp.common.util.JsonUtils;
import com.zxy.btp.common.util.SpringContextUtils;
import com.zxy.ziems.server.alarm.service.AlarmRecordService;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ClientHandlerInitilizer extends ChannelInboundHandlerAdapter {

    private NettyClient nettyClient;
    private AlarmRecordService alarmRecordService;

    public ClientHandlerInitilizer(NettyClient nettyClient) {
        this.nettyClient = nettyClient;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext channelHandlerContext) throws Exception {
        log.info("handlerAdded===={}", JsonUtils.toJSONString(channelHandlerContext));
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.info("handlerRemoved===={}", JsonUtils.toJSONString(ctx));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable throwable) throws Exception {
        log.info("exceptionCaught===={}===={}", JsonUtils.toJSONString(channelHandlerContext), throwable);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info(msg.toString());
        getBean();
        ctx.writeAndFlush("1");
        if (msg instanceof ByteBuf) {
            ByteBuf byteBuf = (ByteBuf) msg;
            log.info("channelRead==ctx=={}", JsonUtils.toJSONString(ctx));
            alarmRecordService.addFireRecord(byteBuf);
        }
    }

    private void getBean() {
        if (alarmRecordService == null) {
            alarmRecordService = SpringContextUtils.getBean(AlarmRecordService.class);
        }
    }

    // channel 处于不活动状态时调用
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.err.println("运行中断开重连。。。");
        nettyClient.connect();
    }

}
